<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属物业" prop="propertyId">
        <el-select v-model="queryParams.propertyId" placeholder="请选择物业" size="mini">
          <el-option v-for="property in propertyListOptions"
                     :key="property.id"
                     :label="property.propertyName"
                     :value="property.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="小区名称" prop="estateName">
        <el-input v-model="queryParams.estateName" placeholder="请输入小区名称" clearable size="mini"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                   v-hasPermi="['module:estate:add']">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                   v-hasPermi="['module:estate:edit']">修改
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
    </el-row>

    <el-table v-loading="loading" :data="estateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"/>
      <el-table-column label="小区ID" align="center" prop="id" width="60"/>
<!--      <el-table-column label="小区名称" align="center" prop="estateName" width="150"/>-->
      <el-table-column label="所属物业" align="center" prop="propertyName" width="110"/>
      <el-table-column label="公告二维码" align="center" width="150">
        <template slot-scope="scope">
          <el-popover placement="right" width="400" trigger="hover">
            <el-image style="width: 380px; height: 380px" :src="scope.row.qrCode" fit="fill"/>
            <i class="el-icon-picture" slot="reference"/>
          </el-popover>
          <el-button size="mini" type="text" icon="el-icon-download"
                     @click="downloadImg(scope.row)">{{ scope.row.estateName }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="负责人" align="center" prop="leaderName"/>
      <el-table-column label="负责人电话" align="center" prop="leaderPhone" width="130"/>
      <el-table-column label="办公室电话" align="center" prop="telphone" width="130"/>
      <!--      <el-table-column label="二维码下载" align="center" width="150">-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-popover placement="right" width="400" trigger="hover">-->
      <!--            <el-image style="width: 380px; height: 380px" :src="scope.row.qrCode"  fit="fill" />-->
      <!--            <i class="el-icon-picture" slot="reference"/>-->
      <!--          </el-popover>-->
      <!--          <el-button size="mini" type="text" icon="el-icon-download"-->
      <!--                     @click="downloadImg(scope.row)">{{scope.row.estateName }}</el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="状态" align="center" prop="state">
        <template slot-scope="scope">
          <div>
            <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="''">正常</el-tag>
            <el-tag v-if="scope.row.state === 1" style="cursor: pointer" :type="'info'">停用</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="420" fixed="right">
        <template slot-scope="scope">
<!--          <el-button size="mini" type="text" icon="el-icon-user-solid">-->
<!--            <router-link :to="'/property/estate/dept?estateId=' + scope.row.id +'&pId=' + scope.row.propertyId"-->
<!--                         class="link-type">-->
<!--              部门人员管理-->
<!--            </router-link>-->
<!--          </el-button>-->
          <el-button size="mini" type="text" icon="el-icon-user-solid" v-hasPermi="['module:estate:propertyRenli']">
            <router-link :to="'/user/dept?estateId=' + scope.row.id" class="link-type"  >
              小区部门管理
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-user-solid">
            <router-link :to="'/property/mer/estate?estateId=' + scope.row.id +'&pId=' + scope.row.propertyId"
                         class="link-type" >
              生活服务管理
            </router-link>
          </el-button>

          <el-button size="mini" type="text" icon="el-icon-user-solid"   v-hasPermi="['module:estate:property']">
            <router-link :to="'/property/estate/build?estateId=' + scope.row.id" class="link-type">
              楼宇列表
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-user-solid"  v-hasPermi="['module:estate:property']">
            <router-link :to="'/property/estate/rooms?estateId=' + scope.row.id" class="link-type">
              物业收费
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-user-solid"  v-hasPermi="['module:estate:property']">
            <router-link :to="'/property/call/center?estateId=' + scope.row.id" class="link-type">
              呼叫中心
            </router-link>
          </el-button>
          <el-button size="mini" type="text" icon="el-icon-picture" @click="resetQrCode(scope.row)"
                     v-hasPermi="['module:patrolPoint:edit']">生成二维码</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['module:estate:edit']"> 修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0"
                :total="total"
                :page.sync="queryParams.pageNum"
                :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 添加或修改小区列对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="13">
            <el-col :span="22">
              <el-form-item label="小区名称" prop="estateName">
                <el-input v-model="form.estateName" placeholder="请输入小区名称" :disabled="form.isCanEdit == 0"
                          size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="名称首字拼音大写" prop="nameCharacter">
                <el-input v-model="form.nameCharacter" :disabled="form.isCanEdit == 0"
                          placeholder="请输入小区名称首字拼音大写" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="所属物业" prop="propertyId">
                <el-select v-model="form.propertyId" placeholder="请选择" :disabled="form.isCanEdit == 0" size="mini"
                           style="width:100%;">
                  <el-option v-for="property in propertyListOptions"
                             :key="property.id"
                             :label="property.propertyName"
                             :value="property.id"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="行政区划" prop="provinceArray" v-if="form.isCanEdit === 1">
                <AreaOptions ref="AreaOptions" v-if="open" pId="15" :value="form.provinceArray"
                             @change="handleChangeProvince"
                             @expand-change="handleExpandChange"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="小区地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入小区地址" :disabled="form.isCanEdit == 0"
                          size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="物业费半年折扣" prop="wyfYhRateHalf">
                <el-input v-model="form.wyfYhRateHalf" type="number" placeholder="请输入物业费半年折扣" size="mini"
                          style="width: 250px">
                  <template slot="append">折</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="物业费一年折扣" prop="wyfYhRate">
                <el-input v-model="form.wyfYhRate" type="number" placeholder="请输入物业费一年折扣" size="mini"
                          style="width: 250px">
                  <template slot="append">折</template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="负责人姓名" prop="leaderName">
                <el-input v-model="form.leaderName" placeholder="请输入负责人姓名" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="负责人电话" prop="leaderPhone">
                <el-input v-model="form.leaderPhone" placeholder="请输入负责人电话" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="办公室电话" prop="telphone">
                <el-input v-model="form.telphone" placeholder="请输入办公室电话" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="22">
              <el-form-item label="支付银行" prop="payPlatformId">
                <el-select v-model="form.payPlatformId" placeholder="请选择支付银行"
                           :disabled="form.payPlatformId!=undefined" style="width:100%;" size="mini" clearable>
                  <el-option v-for="pay in platformList"
                             :key="pay.id"
                             :label="pay.merName"
                             :value="pay.id">
                    {{ pay.merName + " 商户号：" + pay.merNo + " 终端号：" + pay.terminalNo }}
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-col>

          <el-col :span="11">
            <el-col :span="24">
              <div style="width:100%;height:400px;">
                <TianDiTu :zoom="12" :label-title="form.estateName"
                          :default-lat="parseFloat(form.lat)" :default-lng="parseFloat(form.lng)"
                          @pickLngLat="pickLngLat"></TianDiTu>
              </div>
            </el-col>
            <el-col :span="24">
              <el-form-item label="经纬度" prop="lng">
                <el-input v-model="form.lng" placeholder="请输入经度" style="width:47%" size="mini"/>
                <el-input v-model="form.lat" placeholder="请输入纬度" style="width:47%" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="地址" prop="address">
                <el-input v-model="form.address" placeholder="请输入地址" size="mini"/>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="状态" prop="state" :disabled="form.isCanEdit == 0">
                <el-radio-group v-model="form.state" size="mini">
                  <el-radio :value="0" :label="0">正常</el-radio>
                  <el-radio :value="1" :label="1">停用</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-col>

          <el-col :span="24">
            <el-form-item label="费用绑定" prop="wyfWaterBand">
              <el-radio-group v-model="form.wyfWaterBand" size="mini">
                <el-radio :value="0" :label="0">默认</el-radio>
                <el-radio :value="1" :label="1">选中绑定月份之前所有费用</el-radio>
                <el-radio :value="2" :label="2">现有所有未支付费用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 添加或修改小区列对话框 -->
    <el-dialog :title="titleSinglePrice" :visible.sync="openSinglePrice" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="住宅水费单价" prop="waterSinglePrice">
              <el-input v-model="form.waterSinglePrice" placeholder="请输入住宅水费单价" size="mini">
                <template slot="append">元/方</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商铺水费单价" prop="waterBusinessSinglePrice">
              <el-input v-model="form.waterBusinessSinglePrice" placeholder="请输入商铺水费单价" size="mini">
                <template slot="append">元/方</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="住宅电费单价" prop="electricSinglePrice">
              <el-input v-model="form.electricSinglePrice" placeholder="请输入住宅电费单价" size="mini">
                <template slot="append">元/度电</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商铺电费单价" prop="electricBusinessSinglePrice">
              <el-input v-model="form.electricBusinessSinglePrice" placeholder="请输入商铺电费单价" size="mini">
                <template slot="append">元/度电</template>
              </el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="当前抄表年月份" prop="checkMeterYear">
              <el-input v-model="form.checkMeterYear" type="number" placeholder="抄表年份" size="mini"
                        style="width:48%;">
                <template slot="append">年</template>
              </el-input>
              <el-input v-model="form.checkMeterMonth" type="number" placeholder="抄表月份" size="mini"
                        style="width:48%;">
                <template slot="append">月</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" size="mini" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listEstate, getEstate, delEstate, addEstate, updateEstate, resetQrCode} from "@/api/module/estate/estate";
import {listPropertyNoPage} from "@/api/module/property/property";
import Template from "../wx/template";
import {listPay} from "@/api/module/pay/pay";

export default {
  name: "Estate",
  components: {
    Template,
    AreaOptions: () => import('@/components/AreaOptions'),
  },
  data() {
    return {
      map: null,
      marker: null,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      keyword: '',
      // 总条数
      total: 0,
      // 小区列表格数据
      estateList: [],
      // 银行支付列表
      platformList: [],
      //物业公司列表
      propertyListOptions: [],
      // 弹出层标题
      title: "",
      titleSinglePrice: '',
      // 是否显示弹出层
      open: false,
      openSinglePrice: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        propertyId: undefined,
        estateName: undefined,
      },
      // 银行支付查询参数
      queryParamsPay: {
        payPlatformId: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        estateName: [
          {required: true, message: "小区名称不能为空", trigger: "blur"}
        ],
        propertyId: [
          {required: true, message: "请选择所属物业公司", trigger: "blur"}
        ],
        nameCharacter: [
          {required: true, message: "名称首字母不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getPropertyList();
  },
  methods: {
    // TODO：选中节点的值
    handleChangeProvince(e) {
      console.log('handleChangeProvince', e);
      this.form.provinceArray = e;
    },
    // TODO：各父级选项值组成的数组
    handleExpandChange(e) {
      console.log(e);
    },
    /** 查询小区列列表 */
    getList() {
      this.loading = true;
      listEstate(this.queryParams).then(response => {
        this.estateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    pickLngLat(e){
      console.log('getLngLat e === ', e)
      this.form.lng = e.lng.toFixed(6);
      this.form.lat = e.lat.toFixed(6);
    },
    getPlatform() {
      this.loading = true;
      listPay(this.queryParamsPay).then(response => {
        this.platformList = response.rows;
      });
    },
    goUserList(command, row) {
      if (command === 'bandWxUser') {
        this.$router.push("/property/estate/user?estateId=" + row.id);
      } else if (command === 'worker') {
        this.$router.push("/property/worker?estateId=" + row.id + '&type=0');
      } else if (command === 'checkUser') {
        this.$router.push("/property/worker?estateId=" + row.id + '&type=1');
      }
    },
    getPropertyList() {
      listPropertyNoPage().then(response => {
        this.propertyListOptions = response.data;
      });
    },
    getDetail(row) {
      var ss =
        "高层：" + row.wyfHighSinglePrice + "元/平<br/>" +
        "多层：" + row.wyfLowSinglePrice + "元/平<br/>" +
        "商业：" + row.wyfBusinessPrice + "元/平<br/>" +
        "别墅：" + row.wyfVillaSinglePrice + "元/平<br/>" +
        "垃圾处理费：" + row.trashSinglePrice + "元/人<br/>" +
        "水费(民)：" + row.waterSinglePrice + "元/方<br/>" +
        "水费(商)：" + row.waterBusinessSinglePrice + "元/方<br/>" +
        "电费(民)：" + row.electricSinglePrice + "元/度<br/>" +
        "电费(商)：" + row.electricBusinessSinglePrice + "元/度<br/>";
      return ss;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.loading = false,
        this.openSinglePrice = false;
      this.reset();
    },
    downloadImg(row) {
      window.location.href = process.env.VUE_APP_BASE_API + "/common/download/estate/" + row.id;
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        propertyId: undefined,
        estateName: undefined,
        address: undefined,
        prov: undefined,
        city: undefined,
        district: undefined,
        lng: undefined,
        lat: undefined,
        leaderName: undefined,
        leaderPhone: undefined,
        telphone: undefined,
        wyfHighSinglePrice: undefined,
        wyfLowSinglePrice: undefined,
        wyfBusinessPrice: undefined,
        wyfVillaSinglePrice: undefined,
        waterSinglePrice: undefined,
        waterBusinessSinglePrice: undefined,
        trashSinglePrice: undefined,
        electricSinglePrice: undefined,
        electricBusinessSinglePrice: undefined,
        qrCode: undefined,
        state: undefined,
        nameCharacter: undefined,
        provinceArray: undefined,
        wyfYhMonth: undefined,
        wyfYhRate: undefined,
        wyfYhRateHalf: undefined,
        isCanEdit: undefined,
        checkMeterYear: undefined,
        checkMeterMonth: undefined,
        wyfWaterBand: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length
    },
    resetQrCode(row) {
      var data = {
        id: row.id
      };
      resetQrCode(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("生成成功");
          this.getList();
        } else {
          this.msgError("生成失败");
        }
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      var that = this;
      this.reset();
      this.getPlatform();
      this.open = true;
      this.title = "添加小区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      var that = this;
      this.loading = true;
      this.reset();
      this.getPlatform();
      const id = row.id || this.ids;
      getEstate(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改小区";
        console.log("this.form", this.form);
      });
    },
    /** 修改按钮操作 */
    handleUpdateSinglePrice(row) {
      var that = this;
      this.loading = true;
      this.reset();
      const id = row.id || this.ids;
      getEstate(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.openSinglePrice = true;
        this.titleSinglePrice = "修改小区水电费单价";
        console.log("this.form", this.form);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.provinceArray && this.form.provinceArray.length > 0) {
            this.form.prov = this.form.provinceArray[0];
            this.form.city = this.form.provinceArray[1];
            this.form.district = this.form.provinceArray[2];
          }

          if (this.form.id != null) {
            updateEstate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.openSinglePrice = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addEstate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.openSinglePrice = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除小区编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        return delEstate(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
  }
};
</script>
